//
//  Status.swift
//  XYWeibo
//
//  Created by 常晓璇 on 7/1/15.
//  Copyright © 2015 chang xiaoxuan. All rights reserved.
//

import UIKit
import SDWebImage
private let WB_Home_Timeline_URL = "2/statuses/home_timeline.json"

class Status: NSObject {

    // MARK: - 数据模型属性
    /// 微博创建时间
    var created_at: String?
    /// 微博ID
    var id:Int = 0
    /// 微博信息内容
    var text:String?
    /// 微博来源
    var source: String?
    /// 配图数组
    var pic_urls: [[String:String]]? {
        didSet {
            imageURLs = [NSURL]()
            
            for dict in pic_urls! {
                let urlString = dict["thumbnail_pic"]!
                
                imageURLs?.append(NSURL(string: urlString)!)
            }
        }
    }
    
    /// 配图的URL数组
    var imageURLs: [NSURL]?
     /// 用户模型
    var user : User?
    
    static let properties = ["created_at", "id", "text", "source", "pic_urls", "user"]
    
    init(dict: [String : AnyObject]) {
        super.init()
        
        for key in Status.properties {
            if dict[key] == nil || key == "user" {
                continue
            }
            setValue(dict[key], forKey: key)
        }
        
        if let userDict = dict["user"] as? [String : AnyObject] {
            user = User(dict: userDict)
        }
        
    }
    
    
    
    override var description: String {
        let dict = dictionaryWithValuesForKeys(Status.properties)
        return "\(dict)"
    }
    
    class func loadstatus(finished: (statuses: [Status]?, error: NSError?) -> ()) {
        
        assert(sharedUserAccount != nil, "必须登陆之后才能访问网络")
        
        let param = ["access_token" : sharedUserAccount!.access_token]
        NetworkTools.shareNetworkTools().GET(WB_Home_Timeline_URL, parameters: param, success: { (_, JSON) -> Void in
            
            // 从结果中获取微博的数组
            if let array = JSON["statuses"] as? [[String:AnyObject]] {
                let list = statuses(array)
                
                cacheWebImages(list, finished:finished)
                return
            }
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    /// 缓存玩所有图像之后 再通知调用方更新界面
    private class func cacheWebImages(list: [Status], finished: (statuses:[Status]?, error:NSError?) -> ()) {
        // 定义调度组
        let group = dispatch_group_create()
        
        // 遍历数组
        for s in list {
            // 判断imageURLs是否有内容
            if s.imageURLs == nil || s.imageURLs!.isEmpty {
                continue
            }
            // 遍历imageURLs数组 缓存数组中的图片
            for url in s.imageURLs! {
                // 进入组 后续的block代码会受group监听
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) in
                    
                    // 代码执行到此 图片已经缓存完成
                    dispatch_group_leave(group)
                    
                })
            }
        }
        
        // 监听群组调度执行
        dispatch_group_notify(group, dispatch_get_main_queue()) {
            // 完成回调
            finished(statuses: list, error: nil)
        }
    }
    
    ///  使用传入的数组 完成网络模型转 Status 数组
    private class func statuses(array: [[String: AnyObject]]) -> [Status] {
        
        // 定义可变数组
        var arrayM = [Status]()
        
        // 遍历 array
        for dict in array {
            arrayM.append(Status(dict: dict))
        }
        
        return arrayM
    }
    
}
